import service from './Request' //引入api
import type { DtoBase, DtoUpload } from './APIModel' //引入api
//引入api
export enum UploadEventType {
  Avator_Add,
  Test,
  world
}
export enum DownloadType {
  Avator = 'avator',
  Test = 'test',
  world = 'world',
  pdf = 'pdf'
}

export async function uploadSingle(
  file: any,
  param: {
    uploadKey: number | string
    uploadType: number
  }
): Promise<DtoBase> {
  try {
    const formData = new FormData()
    formData.append('file', file)
    // formData.append('uploadKey', param.uploadKey + '')
    formData.append('uploadType', param.uploadType + '')
    const result = (await service.post('/file/upload/single', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })) as DtoBase
    return result
  } catch (error) {
    console.log('uploadSingle API >>>>', error)
    return { code: -1, message: error + '' } as DtoBase
  }
}
export async function download(
  downloadKey?: string,
  downloadType?: DownloadType
): Promise<DtoBase> {
  try {
    const res = await service.post(
      '/file/download/' + downloadType,
      {
        downloadKey: downloadKey,
        downloadType: downloadType
      },
      { responseType: 'blob' }
    )
    if (res.data instanceof Blob) {
      const blob = res.data
      const objectUrl = URL.createObjectURL(blob) //创建下载的链接
      const a = document.createElement('a')
      a.href = objectUrl
      let fileName = 'test.pdf'
      try {
        fileName = res.headers['content-disposition'].split('filename=')[1]
        fileName = decodeURI(fileName)
        console.log('download filename', fileName)
        a.download = fileName //设置文件名
        //下面这个写法兼容火狐
        a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
      } catch (e) {
        console.error('content-disposition filename', e)
      } finally {
        window.URL.revokeObjectURL(objectUrl) //释放bolb对象
      }
      return { code: 0, message: '' } as DtoBase
    } else {
      return { code: -1, message: res.data } as DtoBase
    }

    // } else {
    //   return { code: 0, message: '' } as DtoBase
    // }
  } catch (error) {
    console.log('download API >>>>', error)
    return { code: -1, message: error + '' } as DtoBase
  }
}
